<?php
require_once get_app_location().'/system_message.php';

$request_type=$_POST["requestType"];
if(empty($request_type)){
	die("miss requestType");
}
if($request_type=="create"){
	create_transaction();
}
elseif ($request_type=="delete"){
	delete_transaction();
}
elseif ($request_type=="accept"){
	accept_transaction();
}
  
function create_transaction(){
  global $userid;
  $goods_id=$_POST["goods_id"];
  $type=1;
  if(transaction_over($_POST["target_id"])){
  	die("can't apply this goods");
  }
  if($goods_id=="-"){
  	//reply given
  	$type=2;
  	if($userid==-1){
  		die("invalid user");
  	}
  	else{
  		$goods_id=$userid;
  	}
  }
  $taget_id=$_POST["target_id"];
  $status=1;
  $sql="insert into exc_transaction (createtime,type,goods_id1,goods_id2,status) values"."(now(),".$type.",".$taget_id.",".$goods_id.",".$status.")";
  $result=mysql_query($sql);
  if(!$result){
   die(mysql_error());
  }
  else{
  	generate_message("create",array("type"=>$type,"target"=>$taget_id,"goods"=>$goods_id));
  }
}





function delete_transaction(){
  $trans_id=$_POST["tansactionid"];
  $sql="delete from exc_transaction where id=".$trans_id;
  $res=mysql_query($sql);
  if(!$res){
   echo mysql_error();
   exit();
  }
}

function accept_transaction(){
  $trans_id=$_POST["tansactionid"];
  $sql="update exc_transaction set status=2 where id=".$trans_id;
  $res=mysql_query($sql);
  if(!$res){
   die(mysql_error());
  }
  
  //generate message
  $sql="select * from exc_transaction where id=".$trans_id;
  $res=mysql_query($sql);
  if(!$res){
  	die(mysql_error());
  }
  $row=mysql_fetch_array($res);
  generate_message("accept", array("type"=>$row["type"],"target"=>$row["goods_id1"],"goods"=>$row["goods_id2"]));
  
  //update goods status.
  
  //update related transaction status to 3
  $sql="select type,goods_id1,goods_id2 from exc_transaction where id=".$trans_id;
  $res=mysql_query($sql);
  if(!$res){
   die(mysql_error());
  }
  $row=mysql_fetch_array($res);
  $type=$row["type"];
  $goods1=$row["goods_id1"];
  $goods2=$row["goods_id2"];
  $sql="update exc_transaction set status=3 where id<>".$trans_id." AND goods_id1 =".$goods1;
  $res=mysql_query($sql);
  if(!$res){
   die(mysql_error());
  }
  if($type==1){
  	$sql="update exc_transaction set status=3 where id<>".$trans_id." AND goods_id1 =".$goods2;
  	$res=mysql_query($sql);
  	if(!$res){
  		die(mysql_error());
  	}
  }
  $sql="update exc_transaction set status=3 where id<>".$trans_id." AND goods_id2 =".$goods1;
  $res=mysql_query($sql);
  if(!$res){
   die(mysql_error());
  }
  //update goods status.
  $sql="update exc_goods set status=2 where id=".$goods1;
  $res=mysql_query($sql);
  if(!$res){
   die(mysql_error());
  }
  if($type==1){
  	$sql="update exc_goods set status=2 where id=".$goods2;
  	$res=mysql_query($sql);
  	if(!$res){
  		die(mysql_error());
  	}
  }
}
?>